package com.steven.im.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;

import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.base.Constant;
import com.steven.im.entity.BaseEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.utils.PermissionUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.UserUtils;

import java.lang.ref.WeakReference;

import retrofit2.Response;

/**
 * 欢迎页
 */
public class WelActivity extends AppCompatActivity {

    private static final String TAG = "WelActivity";
    //定义需要申请的相关权限
    private final String[] PERMISSIONS = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE,//存储权限
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_FINE_LOCATION};

    private MyHandler myHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wel);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            View decorView = window.getDecorView();
            decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
                @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    return defaultInsets.replaceSystemWindowInsets(
                            defaultInsets.getSystemWindowInsetLeft(),
                            0,
                            defaultInsets.getSystemWindowInsetRight(),
                            defaultInsets.getSystemWindowInsetBottom());
                }
            });
            ViewCompat.requestApplyInsets(decorView);
            //将状态栏设成透明，如不想透明可设置其他颜色
            window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        }
        myHandler = new MyHandler(this);
        //获取系统参数
        getSystem();
        //获取权限
        getPermission();
    }

    //获取系统参数
    private void getSystem() {
        Task.getApiService().getSystemParam().enqueue(new MyCallback<BaseEntity>(WelActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    SPUtils.put(App.getContext(), "refreshDelayTime", response.body().getResult().getString("refreshDelayTime"));
                    //保存阿里OSS存储信息
                    SPUtils.put(App.getContext(), Constant.AliOOS.KEY_ID,
                            response.body().getResult().getString("aliyuncsOssAccessKeyId"));
                    SPUtils.put(App.getContext(), Constant.AliOOS.KEY_SECRET,
                            response.body().getResult().getString("aliyuncsOssAccessKeySecret"));
                    SPUtils.put(App.getContext(), Constant.AliOOS.BACKET_NAME,
                            response.body().getResult().getString("aliyuncsOssBacketName"));
                    SPUtils.put(App.getContext(), Constant.AliOOS.DOMAIN,
                            response.body().getResult().getString("aliyuncsOssDomain"));
                    SPUtils.put(App.getContext(), Constant.AliOOS.END_POINT,
                            response.body().getResult().getString("aliyuncsOssEndpoint"));

                    //实例化OSS信息
                    ((App) getApplication()).initOSSService();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 获取相关权限
     */
    private void getPermission() {
        PermissionUtils.getInstance().checkPermissions(this, PERMISSIONS, permissionsResult);
    }

    //创建监听权限的接口对象
    PermissionUtils.IPermissionsResult permissionsResult = new PermissionUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            //当提示申请权限时，全部通过，会走这里（6.0以下直接走这里）
            myHandler.sendEmptyMessageDelayed(0, 3000);
        }

        @Override
        public void forbitPermissons() {
            //只要有一个被拒绝，则会走这里，拒绝不在提醒，还是会走这里
            myHandler.sendEmptyMessageDelayed(0, 3000);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        PermissionUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //静态内部类handler，防止内存泄漏
    private static class MyHandler extends Handler {

        private WeakReference<WelActivity> mActivity;

        private MyHandler(WelActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Activity act = mActivity.get();
            if (act != null) {
//                boolean isFirst = (boolean) SPUtils.get(act.getApplicationContext(),
//                        Constant.CommonInfo.IS_FIRST, true);
                //引导页去掉
                boolean isFirst = false;
//                if (isFirst) {//首次打开
//                    act.startActivity(new Intent(act, GuideActivity.class));
//                } else {//非首次打开
                    if (UserUtils.checkLogin()) {
                        act.startActivity(new Intent(act, MainActivity.class));
                    } else {
                        act.startActivity(new Intent(act, ImLoginActivity.class));
                    }
//                }
                act.finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }
}
